package com.zhuoya.healthcard.net;

import com.blankj.utilcode.util.LogUtils;
import com.google.gson.JsonParseException;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * @Author: guolinguang
 * @Date: 2019-06-27 15:07
 * @Description: API请求状态监听
 **/
public class ApiRequestSubscriber<T> implements Observer<ApiFrameResult<T>> {
    /**
     * 服务器成功
     */
    private static final String SERVER_SUCCESS = "200";



    /**
     * 网络错误
     */
    private static final String NET_ERROR = "8080";

    /**
     * 服务器超时
     */
    private static final String TIME_OUT = "8081";

    /**
     * 服务器数据异常
     */
    private static final String SERVER_ERROR = "8082";

    /**
     *未知异常
     */
    private static final String UNKNOWN_ERROR = "8083";


    private ApiRequestCallBack<T> mRequestCallBack;

    public ApiRequestSubscriber(ApiRequestCallBack<T> mRequestCallBack) {
        this.mRequestCallBack = mRequestCallBack;
    }





    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(ApiFrameResult<T> tHttpResult) {
        if (mRequestCallBack != null) {
            String code = tHttpResult.getCode();
            if (SERVER_SUCCESS.equals(code)) {
               T content = tHttpResult.getData();
                try {
                    //防止数据json格式不正确导致崩溃
                    mRequestCallBack.onSuccess(content);
                } catch (Exception e) {
                    LogUtils.e(e.getMessage());
                    mRequestCallBack.onError(SERVER_ERROR, "服务器开小差了，请稍后再试");
                }

            }else {
                mRequestCallBack.onError(code, tHttpResult.getErrorMsg());
            }

        }
    }

    @Override
    public void onError(Throwable e) {
        LogUtils.e(e.getMessage());
        if (e instanceof UnknownHostException) {
            mRequestCallBack.onError(NET_ERROR, "网络异常，请稍后再试");
        } else if (e instanceof SocketTimeoutException) {
            mRequestCallBack.onError(TIME_OUT, "链接超时，请稍后再试");
        } else if (e instanceof JsonParseException) {
            mRequestCallBack.onError(SERVER_ERROR, "数据格式异常");
        }else {
            mRequestCallBack.onError(UNKNOWN_ERROR, "出错了，请稍后再试");
        }


    }

    @Override
    public void onComplete() {

    }


}